package tk.mynoteapp.dev.wechat.pay.common;

import cn.hutool.core.util.StrUtil;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateTimeZoneUtil {
    private static final ZoneId ZONE = ZoneId.systemDefault();
    /**
     * 时间转 TimeZone
     * <p>
     * 2020-08-17T16:46:37+08:00
     *
     * @param time 时间戳
     * @return {@link String}  TimeZone 格式时间字符串
     * @throws Exception 异常信息
     */
    public static String dateToTimeZone(long time) throws Exception {
        return dateToTimeZone(new Date(time));
    }

    /**
     * 时间转 TimeZone
     * <p>
     * 2020-08-17T16:46:37+08:00
     *
     * @param date {@link Date}
     * @return {@link String} TimeZone 格式时间字符串
     * @throws Exception 异常信息
     */
    public static String dateToTimeZone(Date date) throws Exception {
        String time;
        if (date == null) {
            throw new Exception("date is not null");
        }
        ZonedDateTime zonedDateTime = Instant.ofEpochMilli(date.getTime()).atZone(ZONE);
        time = zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx"));
        return time;
    }

    /**
     * TimeZone 时间转标准时间
     * <p>
     * 2020-08-17T16:46:37+08:00 to 2020-08-17 16:46:37
     *
     * @param str TimeZone格式时间字符串
     * @return {@link String} 标准时间字符串
     * @throws Exception 异常信息
     */
    public static String timeZoneDateToStr(String str) throws Exception {
        String time;
        if (StrUtil.isBlank(str)) {
            throw new Exception("str is not null");
        }
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx"));
        if (zonedDateTime == null) {
            throw new Exception("str to zonedDateTime fail");
        }
        time = zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZONE));
        return time;
    }
}
